package cn.fanqinghong.pet.service.impl;

import cn.fanqinghong.basic.service.impl.BaseServiceImpl;
import cn.fanqinghong.pet.domain.PetType;
import cn.fanqinghong.pet.mapper.PetTypeMapper;
import cn.fanqinghong.pet.service.IPetTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fanqinghong
 * @since 2022-06-25
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {
    @Autowired
    private PetTypeMapper PetTypeMapper;

    @Override
    public List<PetType> queryTree() {
        //查询全部的数据
        List<PetType> PetTypes = PetTypeMapper.loadAll();
        //把数据转换成Map的格式，key为id value为查宣导的所有值
        Map<Long, PetType> allPetTypes = PetTypes.stream().collect(Collectors.toMap(PetType::getId, dept -> dept));
        //创建一个List数组用来存取第一级树
        List<PetType> firstPetTypes = new ArrayList<>();
        //遍历循环PetTypes 找到第一个级树
        for (PetType tem : PetTypes) {
            //如果遍历的数据中parent_id为null那么就是第一级树
            if (tem.getPid() == null){
                //把数据存储到第一级树
                firstPetTypes.add(tem);
            }else {
                //这里进入的是子级数，通过department找到夫级数的id，存入父级树的children中
                PetType parent = allPetTypes.get(tem.getPid());
                if (parent != null){
                    parent.getChildren().add(tem);
                }
            }
        }
        //返回第一级树
        return firstPetTypes;
    }
}
